import React from "react";
import productList from "./productList.module.css";
import { Button, Input, Form, DatePicker, Table, Switch, message, Image, Spin } from 'antd';
import { PlusOutlined, DeleteOutlined, SearchOutlined, FormOutlined } from '@ant-design/icons';
import Dialog from "@/components/Dialog";
import { getProduct, addProduct, delProduct, getCategory } from "@/api";




class ProductList extends React.Component {
    constructor() {
        super()
        let _this = this;
        this.state = {
            size: "large",
            columns: [
                {
                    title: '样品图',
                    dataIndex: 'imageUrl',
                    key: "imageUrl"
                },
                {
                    title: '商品类目',
                    dataIndex: 'categoryName',
                    key: "categoryName"
                },
                {
                    title: '商品编号',
                    dataIndex: 'id',
                    key: "id"
                },
                {
                    title: '商品名称',
                    dataIndex: 'name',
                    key: "name"
                },
                {
                    title: '商品价格',
                    dataIndex: 'price',
                    key: "price"
                },
                {
                    title: '是否上架',
                    render() {
                        return <Switch defaultChecked={false} onChange={_this.onChangeSwitch.bind(_this)} />
                    }
                },
                {
                    title: '加入时间',
                    dataIndex: 'time',
                    key: "time"
                },
                {
                    title: '操作',
                    render(row) {
                        return (
                            <div className={productList.optBtn}>
                                <Button
                                    type="primary"
                                    icon={<FormOutlined />}
                                    size={_this.state.size}
                                    onClick={_this.handleUpdate.bind(_this, row)}
                                />
                                <Button
                                    type="danger"
                                    icon={<DeleteOutlined />}
                                    size={_this.state.size}
                                    onClick={_this.handleDel.bind(_this, row)}
                                />
                            </div>
                        )
                    }
                }
            ],
            dataSource: [],
            rowSelection: {
                onChange: (selectedRowKeys, selectedRows) => {
                    console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
                },
                getCheckboxProps: (record) => ({
                    disabled: record.name === 'Disabled User', // Column configuration not to be checked
                    name: record.name,
                }),
            },
            showDialog: false,
            loading: false,
            category: [],
            fromData: {}
        }
    }

    // 是否上架按钮
    onChangeSwitch(checked) {
        console.log(checked);
    }

    // 改变时间时触发
    onChangeDate(date, dateString) {
        console.log(date, dateString);
    }

    // 表格修改信息按钮
    handleUpdate(row) {
        row = {
            ...row,
            imageUrl: row.imageUrl.props.src,
        }

        // this.setState({
        //     showDialog: true,
        //     fromData: row
        // })
    }

    // 表格删除单个按钮
    handleDel(row) {
        delProduct(row.id).then(res => {
            if (res.data.state) {
                message.success(res.data.msg);

                // 重写渲染表格
                this.tableRender();
            } else {
                message.error(res.data.msg);
            }
        })
    }


    // 点击添加商品按钮模态框显示
    dialogVisible() {
        this.setState({
            showDialog: true
        })
    }

    // 模态框确定按钮
    handleSuccess(params) {
        addProduct(params).then(res => {
            if (res.data.state) {
                // 成功提示
                message.success(res.data.msg);
                // 关闭模态框
                this.setState({
                    showDialog: false
                })
            } else {
                message.error("添加失败，是否少写了什么？");
            }
        })
        // 渲染表格
        this.tableRender()
    }


    // 模态框取消按钮
    handleCancel() {
        this.setState({
            showDialog: false
        })
    }


    // 渲染表格方法
    tableRender() {
        this.setState({
            loading: true
        })

        this.category();

        getProduct()
            .then(res => {
                let { data } = res.data;
                let products = data.map(item => {

                    // 通过类目id转化成类目名字
                    let category_name = "";
                    this.state.category.forEach(v => {
                        // 一致情况下给外面字符串赋值类目名
                        if (item.category_id === v.category_id) {
                            category_name = v.categoryName;
                        }
                    })

                    let obj = {
                        imageUrl: <Image width={60} src={item.imageUrl} />,
                        category_id: item.category_id,
                        categoryName: category_name,
                        id: item.product_id,
                        name: item.productName,
                        price: item.price,
                        time: item.updateTime,
                        key: item._id
                    }
                    return obj
                })
                this.setState({
                    dataSource: products,
                    loading: false
                })
            })
    }

    // 获取类目显示类型
    category() {
        getCategory().then(res => {
            this.setState({
                category: res.data.data
            })
        })
    }

    // 发送请求钩子
    componentDidMount() {
        this.tableRender();
    }


    render() {
        const paginationProps = {
            showQuickJumper: false,
            pageSize: 6,
        }

        return (
            <div>
                <Dialog
                    isModalVisible={this.state.showDialog}
                    handleSuccess={this.handleSuccess.bind(this)}
                    handleCancel={this.handleCancel.bind(this)}
                    fromData={this.state.fromData}
                ></Dialog>

                <div className={productList.container}>
                    <h3 className={productList.title}>操作提示</h3>
                    <p><b>1、该页面展示商城所有商品信息，可对商品进行修改操作</b></p>
                    <p><b>2、商家添加商品后，需要重新刷新页面才能看到最新商品</b></p>
                </div>

                <div className={productList.option}>
                    <div className={productList.updateBtn}>
                        <Button type="primary" icon={<PlusOutlined />} size={this.state.size} onClick={this.dialogVisible.bind(this)}>
                            添加商品
                        </Button>
                        <Button type="danger" icon={<DeleteOutlined />} size={this.state.size} className={productList.del}>
                            批量删除
                        </Button>
                    </div>

                    <div className={productList.dateBtn}>
                        <Form.Item label="商品内容：">
                            <Input placeholder="商品名称/编号" />
                        </Form.Item>

                        <Form.Item label="添加时间：">
                            <DatePicker onChange={this.onChangeDate} className={productList.timereset} />
                        </Form.Item>

                        <Button type="primary" icon={<SearchOutlined />} size={this.state.size}>
                            查询
                        </Button>
                    </div>
                </div>

                <Spin tip="少女折寿中..." spinning={this.state.loading}>
                    <Table
                        dataSource={this.state.dataSource}
                        columns={this.state.columns}
                        bordered
                        rowSelection={this.state.rowSelection}
                        pagination={paginationProps}
                    />
                </Spin>
            </div>
        )
    }
}

ProductList.meta = {
    title: "商品列表",
    icon: "icon-liebiao"
}

export default ProductList;